package com.sita.cfmoto.interact.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.sita.cfmoto.R;
import com.sita.cfmoto.event.ReleaseActiveEvent;
import com.sita.cfmoto.interact.activity.ActiveDetailActivity;
import com.sita.cfmoto.interact.activity.ActiveListActivity;
import com.sita.cfmoto.rest.model.Active;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.utils.BeanUtils;
import com.sita.cfmoto.utils.DateUtils;
import com.sita.cfmoto.utils.InteractUtils;
import com.sita.cfmoto.utils.PersistUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class ActiveFragment extends Fragment {
    private final String TAG = ActiveFragment.class.getSimpleName();
    private final int ACTIVE_SOURCE_OFFICIAL = 1;
    private final int ACTIVE_SOURCE_PERSONAL = 0;
    @Bind(R.id.active_fragment_refresh)
    SwipeRefreshLayout refreshActive;
    @Bind(R.id.active_img_01)
    ImageView activeImg01;
    @Bind(R.id.active_name_01)
    TextView activeName01;
    @Bind(R.id.active_organ_01)
    TextView activeOrgan01;
    @Bind(R.id.active_time_01)
    TextView activeTime01;

    @Bind(R.id.active_img_02)
    ImageView activeImg02;
    @Bind(R.id.active_name_02)
    TextView activeName02;
    @Bind(R.id.active_organ_02)
    TextView activeOrgan02;
    @Bind(R.id.active_time_02)
    TextView activeTime02;

    @Bind(R.id.active_img_03)
    ImageView activeImg03;
    @Bind(R.id.active_name_03)
    TextView activeName03;
    @Bind(R.id.active_organ_03)
    TextView activeOrgan03;
    @Bind(R.id.active_time_03)
    TextView activeTime03;
    private int size = 3;
    private int page = 0;
    private Active active01, active02, active03;
    private boolean isRefresh = false;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_active, null);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initOfficialActive();
        initPersonalActive();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        refreshActive.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isRefresh) {
                    isRefresh = true;
                    initOfficialActive();
                    initPersonalActive();
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R.id.active_popular_layout)
    void onPopularClick() {
        if (active01 == null) return;
        Intent intent = new Intent();
        intent.setClass(getActivity(), ActiveDetailActivity.class);
        intent.putExtra("active", active01);
        startActivity(intent);
    }

    @OnClick(R.id.active_latest_layout)
    void onLatestClick() {
        if (active02 == null) return;
        Intent intent = new Intent();
        intent.setClass(getActivity(), ActiveDetailActivity.class);
        intent.putExtra("active", active02);
        startActivity(intent);
    }

    @OnClick(R.id.active_latest_layout1)
    void onLatestOneClick() {
        if (active03 == null) return;
        Intent intent = new Intent();
        intent.setClass(getActivity(), ActiveDetailActivity.class);
        intent.putExtra("active", active03);
        startActivity(intent);
    }

    public void onEventMainThread(ReleaseActiveEvent event) {
        initPersonalActive();
    }

    private void initOfficialActive() {
        InteractUtils.fetchActiveList(1, 1, 0, null, null, null, null, ACTIVE_SOURCE_OFFICIAL, new InteractUtils.FetchActiveListCallback() {
            @Override
            public void onActiveListFetched(List<Active> activeList) {
                refreshActive.setRefreshing(false);
                isRefresh = false;
                if (activeList == null) {
                    activeList = new ArrayList<>();
                }
                if (activeList.isEmpty()) {
                    List<com.sita.cfmoto.persistence.Active> allActive = PersistUtils.getActive(3);
                    Iterator<com.sita.cfmoto.persistence.Active> iterator = allActive.iterator();
                    while (iterator.hasNext()) {
                        com.sita.cfmoto.persistence.Active active = iterator.next();
                        activeList.add(BeanUtils.copyProperties(active));
                    }
                }
                if (activeList.size() == 0) {
                    return;
                }
                try {
                    active01 = activeList.get(0);
                    activeOrgan01.setText(active01.title);
                    activeName01.setText(active01.nickName);
                    Picasso.with(GlobalContext.getGlobalContext()).load((active01.cover.isEmpty() ? null : active01.cover))
                            .placeholder(R.drawable.dynamic_default_rect_bg).centerCrop().fit()
                            .into(activeImg01);

                } catch (IllegalArgumentException exception) {
                    Log.d(TAG, "active fetch list");
                }
            }
        });
    }

    private void initPersonalActive() {
        InteractUtils.fetchActiveList(1, 2, 0, null, null, null, null, ACTIVE_SOURCE_PERSONAL, new InteractUtils.FetchActiveListCallback() {
            @Override
            public void onActiveListFetched(List<Active> activeList) {
                refreshActive.setRefreshing(false);
                isRefresh = false;
                if (activeList != null && activeList.size() > 0) {
                    try {
                        active02 = activeList.get(0);
                        active03 = activeList.size() > 1 ? activeList.get(1) : active02;

                        activeOrgan02.setText(active02.title);
                        activeName02.setText(active02.nickName);
                        activeTime02.setText(GlobalContext.getGlobalContext().getString(R.string.active_time,
                                DateUtils.shortDate(active02.campaignStartTime),
                                DateUtils.shortDate(active02.campaignEndTime)));

                        activeOrgan03.setText(active03.title);
                        activeName03.setText(active03.nickName);
                        activeTime03.setText(GlobalContext.getGlobalContext().getString(R.string.active_time,
                                DateUtils.shortDate(active03.campaignStartTime),
                                DateUtils.shortDate(active03.campaignEndTime)));

                        Picasso.with(GlobalContext.getGlobalContext()).load((active02.cover.isEmpty() ? null : active02.cover))
                                .placeholder(R.drawable.dynamic_default_rect_bg).centerCrop().fit()
                                .into(activeImg02);
                        Picasso.with(GlobalContext.getGlobalContext()).load((active03.cover.isEmpty() ? null : active03.cover))
                                .placeholder(R.drawable.dynamic_default_rect_bg).centerCrop().fit()
                                .into(activeImg03);
                    } catch (IllegalArgumentException exception) {
                        Log.d(TAG, "active fetch list");
                    }
                }
            }
        });
    }

    @OnClick(R.id.official_more)
    void onClickOfficalMore() {
//        Intent intent = new Intent();
//        intent.setClass(getActivity(), ActiveListActivity.class);
        startActivity(ActiveListActivity.newIntent(getActivity(), ACTIVE_SOURCE_OFFICIAL));
    }

    @OnClick(R.id.personal_more)
    void onClickPersonalMore() {
//        Intent intent = new Intent();
//        intent.setClass(getActivity(), ActiveListActivity.class);
        startActivity(ActiveListActivity.newIntent(getActivity(), ACTIVE_SOURCE_PERSONAL));
    }


}
